package com.september.concurrent;

import java.net.UnknownHostException;
import java.util.List;
import java.util.concurrent.Semaphore;

import com.google.code.morphia.Datastore;
import com.september.mongo.data.DataProvider;
import com.september.prop.Properteer;
import com.september.util.BaseData;
import com.september.util.Reader;

public class InserterThread<T extends BaseData> extends Thread{
	
	private String name;
	private Semaphore semaphore;
	private BaseData entity;
	private Thread parent;
	
	
		
	public <T extends BaseData> InserterThread(T  entity,String name, Semaphore sem, Thread parent) {
	    this.name = name;
	    this.semaphore = sem;
	    this.parent = parent;
	    this.entity = entity;
	  }
	
	public void run() {
		try {
			if(parent!= null) {
				parent.join();
			}
			semaphore.acquire();
			criticalCode();
			semaphore.release();
		} catch (InterruptedException e) {
			Properteer.getInstance().getLogger(InserterThread.class).error(e.getClass().getName(),e);
		} catch (UnknownHostException e) {
			Properteer.getInstance().getLogger(InserterThread.class).error(e.getClass().getName(),e);
		}
		
	}
	
	private void criticalCode() throws UnknownHostException{
		
		Datastore ds = (new DataProvider()).getDatastore();

				
		Properteer.getInstance().getLogger(InserterThread.class).debug("T:"+this.getId()+"\tReading: " +name);
		try {
			List<T> innerList = (List<T>) Reader.read(entity.getClass().newInstance(),name,entity.getOrdreredField());
			Properteer.getInstance().getLogger(InserterThread.class).debug("T:"+this.getId()+"\ttry to saving:\t "+innerList.size()+" record of type: \t"+entity.getClass().getName());
			int counter = 0;
			for(T element: innerList) {
				
				element.manageRefernces();
				
				ds.save(element);
				counter++;
				
			}
			
			Properteer.getInstance().getLogger(InserterThread.class).debug("T:"+this.getId()+"\tsaved:\t "+counter+" record of type: \t"+entity.getClass().getName());
		}
		
		catch (Exception e) {
			Properteer.getInstance().getLogger(InserterThread.class).error(e.getClass().getName(),e);
		}
		
		
	}
		
}
